#include "requestdispatcher.h"

#include "irequestclient.h"

namespace tool {

RequestDispatcher::RequestDispatcher() {

}

RequestDispatcher::~RequestDispatcher() {

}

void RequestDispatcher::AddRequestClient(IRequestClient* client) {
	REQUEST_LIST request_list;

	client->RequestList(request_list);

	for(REQUEST_LIST::iterator it = request_list.begin(); it != request_list.end(); it++) {
		request_client_map[*it].push_back(client);
	}
}

void RequestDispatcher::RemoveRequestClient(IRequestClient* client) {
	REQUEST_LIST request_list;

	client->RequestList(request_list);

	for(REQUEST_LIST::iterator it = request_list.begin(); it != request_list.end(); it++) {
		REQUEST_CLIENT_MAP::iterator it1 = request_client_map.find(*it);

		if(it1 == request_client_map.end()) {
			continue;
		}

		REQUEST_CLIENT_LIST::iterator it2 = it1->second.begin();
		for(; it2 != it1->second.end(); it2++) {
			if(*it2 == client) {
				it1->second.erase(it2);
				break;
			}
		}
	}
}

void RequestDispatcher::OnRequest(pack::Request& request) {
	bool is_handler = false;
	uint32_t uri = request.GetUri();

	REQUEST_CLIENT_LIST::const_iterator it;
	REQUEST_CLIENT_LIST& request_client_list = GetRequestClient(uri);
	for(it = request_client_list.begin(); it != request_client_list.end(); it++) {
		(*it)->OnRequest(request);

		is_handler = true;
	}

	if(is_handler == false) {

	}
}

std::list<IRequestClient*>& RequestDispatcher::GetRequestClient(uint32_t uri) {
	REQUEST_CLIENT_MAP::iterator it = request_client_map.find(uri);

	if(it == request_client_map.end()) {
		return null_client_list;
	}
	return it->second;
}

}
